package com.changgou.log.aspect;


import com.changgou.log.feign.SystemLogFeign;
import com.changgou.log.pojo.SystemLog;
import com.changgou.log.utils.GetAddressIp;
import com.changgou.utils.TokenDecode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAspect {


    @Autowired
    private SystemLogFeign systemLogFeign;


    @Autowired
    private HttpServletRequest request;


    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 使用环绕通知对controller方法进行增强：自动记录日志
     */
    @Around("execution(* com.changgou.*.controller.*.*(..))")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        //获取登录的账号信息
        String username = tokenDecode.getUserInfo().get("username");
        // 获取方法名称 类全名
        String methodName = pjp.getSignature().getName();
        String fullClassName = pjp.getTarget().getClass().getName();

        //Syslog对象
        SystemLog log = new SystemLog();
        log.setTime(new Date());
        if (username != null) {
            log.setUserName(username);

        } else {
            log.setUserName("");
        }
        log.setIp(GetAddressIp.getIpAddr(request));
        log.setMethod(methodName);
        log.setAction(fullClassName + "." + methodName);

        systemLogFeign.add(log);
        return pjp.proceed();


    }

}
